"""
AI智能体模块 - 基于LangChain + Azure OpenAI
用于文本信息提取和客户识别
"""
import json
import re
from typing import Dict, Any, List, Optional
from dataclasses import dataclass
import logging

# LangChain imports
from langchain_openai import AzureChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field
from datetime import datetime
logger = logging.getLogger(__name__)

# Azure OpenAI 配置
OPENAI_API_KEY = "BceA7CirbOy5DZt9rTRKCmetiLGhT1zG9PU9ANxGvYb5VTdtbYNbJQQJ99BCACHYHv6XJ3w3AAAAACOG99NH"
AZURE_ENDPOINT = "https://ftii-m7yk703e-eastus2.cognitiveservices.azure.com"
DEPLOYMENT_NAME = "gpt-4o"
API_VERSION = "2025-01-01-preview"

# Pydantic 模型用于结构化输出
class ContactInfoSchema(BaseModel):
    """联系信息结构化模型"""
    name: Optional[str] = Field(None, description="个人姓名")
    company: Optional[str] = Field(None, description="公司名称")
    address: Optional[str] = Field(None, description="地址信息")
    phone: Optional[str] = Field(None, description="电话号码")
    website: Optional[str] = Field(None, description="网站链接")
    summary: Optional[str] = Field(None, description="个人或公司简介")
    is_company: bool = Field(False, description="是否为公司")

class CustomerInsightSchema(BaseModel):
    """客户洞察结构化模型"""
    is_potential_customer: bool = Field(description="是否为潜在客户")
    confidence_score: float = Field(description="置信度评分(0.0-1.0)")
    customer_type: str = Field(description="客户类型：product_customer(产品客户), job_seeker(求职者), partner(合作伙伴), social_comment(社交评论), other(其他)")
    reason: str = Field(description="分析原因")
    needs: List[str] = Field(default=[], description="识别的需求列表")

@dataclass
class ContactInfo:
    """联系信息数据结构"""
    name: Optional[str] = None
    company: Optional[str] = None
    address: Optional[str] = None
    phone: Optional[str] = None
    website: Optional[str] = None
    summary: Optional[str] = None
    is_company: bool = False

@dataclass
class CustomerInsight:
    """客户洞察数据结构"""
    user_name: str
    content: str
    is_potential_customer: bool
    confidence_score: float
    customer_type: str
    reason: str
    needs: List[str]


class AIAgent:
    """AI智能体基类 - 基于LangChain"""
    
    def __init__(self, temperature: float = 0.1):
        """初始化LangChain Azure OpenAI"""
        self.llm = AzureChatOpenAI(
            azure_endpoint=AZURE_ENDPOINT,
            azure_deployment=DEPLOYMENT_NAME,
            api_version=API_VERSION,
            api_key=OPENAI_API_KEY,
            temperature=temperature,
            max_tokens=2000,
        )
        logger.info("LangChain Azure OpenAI 初始化成功")



class CustomerAnalyzer(AIAgent):
    """客户分析智能体 - 基于LangChain"""
    
    def __init__(self, temperature: float = 0.1):
        super().__init__(temperature)
        
        # 创建JSON输出解析器
        self.parser = JsonOutputParser(pydantic_object=CustomerInsightSchema)
        
        # 创建提示模板
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", """你是一个专业的客户分析专家。请分析用户的评论内容，判断评论者是否对帖子内容中提到的产品/服务/机会感兴趣的潜在客户。

分析重点：
1. **帖子内容理解**: 首先分析帖子内容(summary)中提到了什么产品、服务、工作机会或业务
2. **评论意图分析**: 评论者的回复是否表达了对帖子中内容的兴趣、需求或咨询意向
3. **客户类型识别**: 
   - 产品/服务客户：对帖子中产品或服务感兴趣，可能想购买或了解
   - 求职者：对招聘信息感兴趣的求职者
   - 合作伙伴：对业务合作感兴趣的潜在合作方
   - 其他商业机会

判断标准：
1. 是否表达了明确的兴趣或询问（如"Still hiring?", "详细信息", "价格多少"）
2. 是否询问具体细节（规格、价格、联系方式、要求等）
3. 是否表现出购买/合作/应聘意向
4. 是否有相关的专业背景或需求
5. 是否表现出时间紧迫性

特殊情况处理：
- 简单的社交评论（如"Nice", "Way to go", "👍"）通常不是潜在客户
- 单纯的点赞或礼貌性回复不算商业兴趣
- 要区分求职者、客户、合作伙伴等不同类型的潜在目标

评分标准：
- 0.8-1.0: 高意向客户（明确表达需求+具体询问+相关背景）
- 0.6-0.8: 中等意向客户（表现兴趣+部分询问）
- 0.3-0.6: 低意向客户（轻微兴趣但无明确行动意向）
- 0.0-0.3: 非目标客户（社交评论、无关回复、纯礼貌性互动）

{format_instructions}"""),
            ("human", """用户名：{user_name}
用户内容：{content}

请分析这个评论者是否是对帖子内容感兴趣的潜在客户。""")
        ])
        
        # 创建处理链
        self.chain = self.prompt | self.llm | self.parser
    
    def analyze_potential_customers(self, user_contents: List[Dict[str, str]]) -> List[CustomerInsight]:
        """分析潜在客户列表
        
        Args:
            user_contents: 格式 [{"user_name": "用户名", "content": "用户说的内容"}, ...]
        
        Returns:
            List[CustomerInsight]: 客户洞察列表
        """
        try:
            results = []
            
            for user_data in user_contents:
                user_name = user_data.get('user_name', '')
                content = user_data.get('content', '')
                
                if not user_name or not content:
                    continue
                
                insight = self._analyze_single_customer(user_name, content)
                results.append(insight)
            
            return results
            
        except Exception as e:
            logger.error(f"分析潜在客户失败: {str(e)}")
            return []
    
    def _analyze_single_customer(self, user_name: str, content: str) -> CustomerInsight:
        """分析单个客户"""
        try:
            # 获取格式化指令
            format_instructions = self.parser.get_format_instructions()
            
            # 执行链
            result = self.chain.invoke({
                "user_name": user_name,
                "content": content,
                "format_instructions": format_instructions
            })
            
            # 转换为CustomerInsight对象
            return CustomerInsight(
                user_name=user_name,
                content=content,
                is_potential_customer=bool(result.get('is_potential_customer', False)),
                confidence_score=float(result.get('confidence_score', 0.0)),
                customer_type=result.get('customer_type', 'other'),
                reason=result.get('reason', ''),
                needs=result.get('needs', [])
            )
            
        except Exception as e:
            logger.error(f"分析单个客户失败: {str(e)}")
            return CustomerInsight(
                user_name=user_name,
                content=content,
                is_potential_customer=False,
                confidence_score=0.0,
                customer_type='other',
                reason=f"分析错误: {str(e)}",
                needs=[]
            )



def analyze_facebook_comments(comments_data: List[Dict]) -> List[Dict]:
    """
    分析Facebook评论数据，判断评论者是否为潜在客户
    
    Args:
        comments_data: Facebook评论数据列表，每个元素包含platform, summary, comment_name, comment_text等字段
        
    Returns:
        添加了AI分析结果的评论数据列表
    """
    if not comments_data:
        return comments_data
    
    try:
        analyzer = CustomerAnalyzer()
        
        # 准备AI分析的数据格式
        user_contents = []
        for comment in comments_data:
            user_name = comment.get('comment_name', '')
            comment_text = comment.get('comment_text', '')
            summary = comment.get('summary', '')
            
            # 构建完整的上下文，包含帖子内容和评论内容
            context = f"帖子内容: {summary}\n评论内容: {comment_text}"
            
            user_contents.append({
                'user_name': user_name,
                'content': context
            })
        
        # 进行AI分析
        insights = analyzer.analyze_potential_customers(user_contents)
        
        # 将分析结果添加到原始评论数据中
        analyzed_comments = []
        for i, comment in enumerate(comments_data):
            # 复制原始评论数据
            analyzed_comment = comment.copy()
            
            # 添加AI分析结果
            if i < len(insights):
                insight = insights[i]
                analyzed_comment['is_potential_customer'] = insight.is_potential_customer
                analyzed_comment['confidence_score'] = insight.confidence_score
                analyzed_comment['customer_type'] = insight.customer_type
                analyzed_comment['analysis_reason'] = insight.reason
                analyzed_comment['identified_needs'] = insight.needs
            else:
                analyzed_comment['is_potential_customer'] = False
                analyzed_comment['confidence_score'] = 0.0
                analyzed_comment['customer_type'] = 'other'
                analyzed_comment['analysis_reason'] = "分析失败"
                analyzed_comment['identified_needs'] = []
            
            analyzed_comments.append(analyzed_comment)
        
        return analyzed_comments
        
    except Exception as e:
        logger.error(f"分析Facebook评论失败: {str(e)}")
        # 如果分析失败，返回原始数据但添加默认分析字段
        for comment in comments_data:
            comment['is_potential_customer'] = False
            comment['confidence_score'] = 0.0
            comment['customer_type'] = 'other'
            comment['analysis_reason'] = f"分析失败: {str(e)}"
            comment['identified_needs'] = []
        return comments_data



class CustomerChatAgent(AIAgent):
    """单个公司客户聊天智能体 - 代表特定公司与潜在客户对话"""
    
    def __init__(self, company_info: Dict[str, str], temperature: float = 0.8):
        super().__init__(temperature)
        self.company_info = company_info
        
        # 创建对话提示模板
        self.dialogue_prompt = ChatPromptTemplate.from_messages([
            ("system", """你代表{company_name}公司与潜在客户进行专业对话。

公司信息：
- 公司名称：{company_name}
- 主营业务：{company_business}
- 主要产品/服务：{products_services}

对话要求：
1. 清晰表明你代表的公司身份
2. 友好专业地了解客户需求
3. 提供相关的产品/服务信息
4. 适时引导下一步行动（演示、报价、会议等）
5. 保持对话自然流畅

请基于对话历史生成合适的回复："""),
            ("human", """客户名称：{customer_name}
对话历史：
{conversation_history}

客户最新消息：{latest_message}

请生成专业回复：""")
        ])
        
        # 开场白提示模板
        self.opening_prompt = ChatPromptTemplate.from_messages([
            ("system", """你代表{company_name}公司向潜在客户发送开场白。

公司业务：{company_business}

请生成友好专业的开场白消息："""),
            ("human", "客户名称：{customer_name}")
        ])
        
        # 创建处理链
        self.dialogue_chain = self.dialogue_prompt | self.llm
        self.opening_chain = self.opening_prompt | self.llm
    
    def generate_opening(self, customer_name: str = "客户") -> Dict[str, Any]:
        """生成开场白消息"""
        try:
            response = self.opening_chain.invoke({
                "company_name": self.company_info.get('name', '我们公司'),
                "company_business": self.company_info.get('business', ''),
                "customer_name": customer_name
            })
            
            return {
                "success": True,
                "message": response.content.strip(),
                "message_type": "opening",
                "customer_name": customer_name,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error(f"生成开场白失败: {str(e)}")
            return {
                "success": False,
                "message": f"""您好{customer_name}！我是{self.company_info.get('name', '我们公司')}的代表。

我们专注于{self.company_info.get('business', '相关领域')}，很高兴与您联系。""",
                "message_type": "opening",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
    
    def generate_response(self, 
                         conversation_history: List[Dict], 
                         latest_message: str,
                         customer_name: str = "客户") -> Dict[str, Any]:
        """生成对话回复"""
        try:
            # 格式化对话历史
            formatted_history = self._format_conversation_history(conversation_history)
            
            # 生成回复
            response = self.dialogue_chain.invoke({
                "company_name": self.company_info.get('name', '我们公司'),
                "company_business": self.company_info.get('business', ''),
                "products_services": self.company_info.get('product_service', ''),
                "customer_name": customer_name,
                "conversation_history": formatted_history,
                "latest_message": latest_message
            })
            
            return {
                "success": True,
                "message": response.content.strip(),
                "message_type": "response",
                "customer_name": customer_name,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            logger.error(f"生成回复失败: {str(e)}")
            return {
                "success": False,
                "message": f"您好{customer_name}！感谢您的消息。请问您对{self.company_info.get('business', '我们的服务')}有什么具体问题吗？",
                "message_type": "response",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
    
    def chat(self, 
            conversation_history: List[Dict] = None,
            customer_message: str = None,
            customer_name: str = "客户") -> Dict[str, Any]:
        """主要的聊天接口"""
        conversation_history = conversation_history or []
        
        if not conversation_history and not customer_message:
            # 全新对话，生成开场白
            return self.generate_opening(customer_name)
        
        elif not customer_message:
            # 有历史记录但没有新消息，生成跟进消息
            if conversation_history:
                # 基于最后一条消息生成跟进
                last_message = conversation_history[-1].get('content', '')
                return self.generate_response(
                    conversation_history[:-1],  # 排除最后一条
                    f"基于之前的对话继续交流：{last_message}",
                    customer_name
                )
            else:
                return self.generate_opening(customer_name)
        
        else:
            # 有客户新消息，生成回复
            return self.generate_response(conversation_history, customer_message, customer_name)
    
    def _format_conversation_history(self, messages: List[Dict]) -> str:
        """格式化对话历史"""
        if not messages:
            return "暂无对话历史"
            
        formatted = []
        for i, msg in enumerate(messages[-8:], 1):  # 最近8条消息
            sender = msg.get('sender', '')
            content = msg.get('content', '')
            role = "客户" if "customer" in sender.lower() or "client" in sender.lower() else "代表"
            formatted.append(f"{role}：{content}")
        
        return "\n".join(formatted)


class ConversationManager:
    """对话管理器 - 管理单个公司的客户对话"""
    
    def __init__(self, company_info: Dict[str, str]):
        self.agent = CustomerChatAgent(company_info)
        self.conversations = {}  # conversation_id -> conversation_data
    
    def start_conversation(self, customer_info: Dict[str, str] = None) -> str:
        """开始新对话"""
        conversation_id = f"conv_{int(datetime.now().timestamp())}"
        customer_name = customer_info.get('name', '客户') if customer_info else '客户'
        
        # 生成开场白
        result = self.agent.generate_opening(customer_name)
        
        # 保存对话记录
        self.conversations[conversation_id] = {
            'customer_info': customer_info or {'name': customer_name},
            'messages': [
                {
                    'sender': 'AI_Representative',
                    'content': result['message'],
                    'timestamp': datetime.now().isoformat(),
                    'type': 'opening'
                }
            ],
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }
        
        return conversation_id
    
    def send_message(self, 
                    conversation_id: str, 
                    customer_message: str,
                    customer_name: str = None) -> Dict[str, Any]:
        """发送消息并获取回复"""
        if conversation_id not in self.conversations:
            raise ValueError(f"对话 {conversation_id} 不存在")
        
        conversation = self.conversations[conversation_id]
        customer_info = conversation['customer_info']
        customer_name = customer_name or customer_info.get('name', '客户')
        
        # 添加客户消息到对话记录
        customer_msg = {
            'sender': 'Customer',
            'content': customer_message,
            'timestamp': datetime.now().isoformat(),
            'type': 'customer'
        }
        conversation['messages'].append(customer_msg)
        
        # 获取AI回复
        result = self.agent.chat(
            conversation_history=conversation['messages'][:-1],  # 排除刚添加的客户消息
            customer_message=customer_message,
            customer_name=customer_name
        )
        
        # 添加AI回复到对话记录
        ai_msg = {
            'sender': 'AI_Representative',
            'content': result['message'],
            'timestamp': datetime.now().isoformat(),
            'type': 'ai_response'
        }
        conversation['messages'].append(ai_msg)
        conversation['updated_at'] = datetime.now().isoformat()
        
        return {
            'conversation_id': conversation_id,
            'customer_message': customer_message,
            'ai_response': result['message'],
            'success': result['success'],
            'timestamp': datetime.now().isoformat()
        }
    
    def get_conversation_history(self, conversation_id: str) -> List[Dict]:
        """获取对话历史"""
        if conversation_id not in self.conversations:
            return []
        return self.conversations[conversation_id]['messages']
    
    def get_all_conversations(self) -> Dict[str, Any]:
        """获取所有对话摘要"""
        summary = {}
        for conv_id, conv_data in self.conversations.items():
            summary[conv_id] = {
                'customer_name': conv_data['customer_info'].get('name', '客户'),
                'message_count': len(conv_data['messages']),
                'last_updated': conv_data['updated_at'],
                'created_at': conv_data['created_at']
            }
        return summary


# 使用示例
def main():
    # 公司信息配置
    company_info = {
        'name': '云端科技解决方案有限公司',
        'business': '企业级云计算和数字化转型服务',
        'product_service': '云服务器、SaaS平台、数字化咨询'
    }
    
    # 创建对话管理器
    manager = ConversationManager(company_info)
    
    # 开始新对话
    print("=== 开始新对话 ===")
    conv_id = manager.start_conversation({
        'name': '张经理',
        'industry': '制造业',
        'company': '创新制造有限公司'
    })
    
    # 获取开场白
    history = manager.get_conversation_history(conv_id)
    opening_message = history[0]['content']
    print(f"AI开场白：{opening_message}")
    print()
    
    # 客户回复
    print("=== 客户第一次回复 ===")
    result1 = manager.send_message(
        conversation_id=conv_id,
        customer_message='你好，我们对云计算服务感兴趣，能介绍一下吗？',
        customer_name='张经理'
    )
    print(f"客户：{result1['customer_message']}")
    print(f"AI回复：{result1['ai_response']}")
    print()
    
    # 继续对话
    print("=== 客户第二次回复 ===")
    result2 = manager.send_message(
        conversation_id=conv_id,
        customer_message='我们主要需要数据存储和协同办公的解决方案，有什么推荐吗？',
        customer_name='张经理'
    )
    print(f"客户：{result2['customer_message']}")
    print(f"AI回复：{result2['ai_response']}")
    print()
    
    # 查看对话历史
    print("=== 完整对话历史 ===")
    full_history = manager.get_conversation_history(conv_id)
    for i, msg in enumerate(full_history, 1):
        sender = "AI代表" if msg['sender'] == 'AI_Representative' else "客户"
        print(f"{i}. {sender}：{msg['content']}")
    
    # 查看所有对话
    print("\n=== 所有对话摘要 ===")
    all_convos = manager.get_all_conversations()
    for conv_id, info in all_convos.items():
        print(f"对话ID：{conv_id}，客户：{info['customer_name']}，消息数：{info['message_count']}")


if __name__ == "__main__":
    main()